package com.gadgets.busi.dataanalysis.registry.task;

import com.alibaba.fastjson.JSON;
import com.gadgets.busi.bm02.common.GadgetsBm02Constant;
import com.gadgets.busi.bm02.pojo.MaterialRecipe;
import com.gadgets.framework.common.util.StringUtils;
import com.gadgets.framework.thread.task.AbstractRunnable;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-12-01
 *
 */
public class DataAnalysisClusterRunnable extends AbstractRunnable {

    public DataAnalysisClusterRunnable(List<MaterialRecipe> workList) {
        this.workList.addAll(workList);
        setModuelNo(GadgetsBm02Constant.DA_MODUEL_NO);
    }

    /**
     * 待聚合数据
     */
    private final List<MaterialRecipe> workList = new ArrayList<>();
    /**
     * 已聚合数据
     */
    private final HashMap<Long,HashMap<String,List<MaterialRecipe>>> clusterResult = new HashMap<>();

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try {
            logger.debug("数据聚合任务{}开始执行",getTaskNo());
            for (MaterialRecipe recipe : workList) {
                logger.debug("执行数据：{}", JSON.toJSONString(recipe));
                Long targetMaterialId = recipe.getTargetMeterialId();
                if(!clusterResult.containsKey(targetMaterialId)){
                    clusterResult.put(targetMaterialId,new HashMap<>());
                }
                HashMap<String,List<MaterialRecipe>> recipeMap = clusterResult.get(targetMaterialId);
                String batchNo = recipe.getBatchNo();
                if(!recipeMap.containsKey(batchNo)){
                    recipeMap.put(batchNo,new ArrayList<>());
                }
                recipeMap.get(batchNo).add(recipe);
            }
            taskFinish();
            logger.debug("线程任务{}执行完成",getTaskNo());
        } catch (Exception exception) {
            logger.error("时间{}，数据聚合发生异常！", new Date());
            logger.error(StringUtils.formatExceptionStack(exception));
            setStatus(1);
        }
    }

    public HashMap<Long, HashMap<String,List<MaterialRecipe>>> getClusterResult() {
        return clusterResult;
    }

}
